package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 增加角色
     * @param role
     */
    @Override
    public void add(Role role) {
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        roleMapper.insertSelective(role);
    }

    /**
     * 修改角色
     * @param role
     */
    @Override
    public void edit(Role role) {
        role.setUpdateTime(new Date());
        roleMapper.updateByPrimaryKeySelective(role);
    }

    /**
     * 删除角色
     * @param role
     */
    @Override
    public void delete(Role role) {
        role.setStatus(0);
        roleMapper.updateByPrimaryKeySelective(role);
    }

    /**
     * 分页查询
     * @param searchMap
     * @return
     */
    @Override
    public Page<Role> findPage(Map<String, Object> searchMap) {

        Integer currentPage=null;
        if(searchMap.get("currentPage")!=null){
            currentPage = (Integer) searchMap.get("currentPage");
        }else {
            currentPage =1;
        }
        Integer pageSize=null;
        if( searchMap.get("pageSize")!=null){
            pageSize = (Integer) searchMap.get("pageSize");
        }else {
            pageSize=10;
        }

        Example example=createExample(searchMap);
        PageHelper.startPage(currentPage,pageSize);
        return (Page<Role>) roleMapper.selectByExample(example);
    }

    /**
     * 封装查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap.get("uid")!=null&&!"".equals(searchMap.get("uid"))){
            criteria.andEqualTo("uid",searchMap.get("uid"));
        }
        if(searchMap.get("roleName")!=null&&!"".equals(searchMap.get("roleName"))){
            criteria.andLike("content","%"+searchMap.get("roleName")+"%");
        }

        return example;
    }
}
